package com.suray.attendance.controller;


import com.suray.attendance.common.dingding.service.DingAccessTokenService;
import com.suray.attendance.common.utils.LoggerUtil;
import com.suray.attendance.contacts.service.DingDeptService;
import com.suray.attendance.db.service.DingDeptDBService;
import com.suray.attendance.model.pojo.DeptInfo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: jianglinyu
 * @CreateTime: 2023-07-10  14:20
 * @Description: 钉钉组织架构的部门操作接口类
 * @Version: 1.0
 */
@CrossOrigin
@RequestMapping("/api/dingDept")
@RestController
@CommonsLog
public class DingDeptController {

    @Resource
    private DingDeptDBService dingDeptDBService;
    @Resource
    private DingDeptService dingDeptService;
    @Resource
    private DingAccessTokenService dingAccessTokenService;

    /**
     * @description:  根据用户id获取用户钉钉详细信息
     * @author: jianglinyu
     * @date: 2023/7/5 15:18
     * @param: [userId]
     * @return: java.lang.String
     **/
    @PostMapping(value = "/insertOrUpdateDingDeptInfo")
    @ApiOperation(value = "根据部门pid更新根部门下子部门下的所有部门信息")
    public void  insertOrUpdateDingDeptInfo(){
        // 获取钉钉的accessToken
        String accessToken = dingAccessTokenService.getAccessToken();
        List<DeptInfo> dingDeptInfoByPid = dingDeptService.getDingDeptInfoFromDingDing(accessToken, 1L);
        dingDeptDBService.insertOrUpdateDingDeptDB(dingDeptInfoByPid);

//        List<DeptInfo> dingDeptInfo = dingDeptService.getDingDeptInfo(1L);
//        dingDeptService.insertOrUpdateDingDeptDB(dingDeptInfo);
        getDeptInfoByPidToInsertDb(accessToken,1L);
    }

    private void getDeptInfoByPidToInsertDb(String accessToken,Long pid) {
        List<Long> longs = dingDeptDBService.getDingDeptByPid(pid);
        if (longs!=null && longs.size()>0){
            // 该部门有子部门
            longs.stream().forEach(id->{
                try {
                    // 将这个从数据库中查询出来id作为pid去钉钉中查询它的子部门信息
                    List<DeptInfo> dingDeptInfoFromDingDing = dingDeptService.getDingDeptInfoFromDingDing(accessToken,id);
                    if(dingDeptInfoFromDingDing!=null && dingDeptInfoFromDingDing.size()>0){
                        dingDeptDBService.insertOrUpdateDingDeptDB(dingDeptInfoFromDingDing);
                        getDeptInfoByPidToInsertDb(accessToken,id);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    LoggerUtil.error("获取父id="+id+"时出现异常"+e.getMessage(),DingDeptController.class);
                }
            });
        }
    }
}